const requestSender = require('request-promise-native');

const router = require('koa-router')();
router.prefix('/login/third')

const GihubConfig = {
    client_id : "562d0f****cc8d2ac6da",
    client_secret : "f6b89edd2d****0d93d36c2b53b519daff7*****"
}

//点击Github第三方访问
router.get("/github/req", async(ctx, next)=>{
    let path = `https://github.com/login/oauth/authorize?client_id=${GihubConfig.client_id}&allow_signup=false&state=114514`;
    ctx.redirect(path);
});

//接收github回调
router.get('/github/callback', async(ctx, next)=>{
    console.log(ctx.query);  //{ code: 'f4645ded78fee2e0bbf3', state: '114514(请求authorize时发送给github的state)' }
    const code = ctx.query.code;

    //请求access_token的request                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
    var tokenOptions = {
        method: 'POST',
        uri: 'https://github.com/login/oauth/access_token',
        body: {
            client_id: GihubConfig.client_id,
            client_secret: GihubConfig.client_secret,
            code: code //使用code
        },
        json: true
    };
    var tokenResponse = await requestSender(tokenOptions);
    var access_token = tokenResponse.access_token;
    console.log(tokenResponse);
    /*
    {
        access_token: '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',
        token_type: 'bearer',
        scope: ''
    }
    */

    //请求用户信息的request
    var dataOptions = {
        method: 'GET',
        uri: 'https://api.github.com/user',
        headers: {
            'User-Agent': 'OAuthTestGithub', //User-Agent内容要填你在github设置的application名，不然会403
            'Authorization': 'token ' + access_token
        }
    }
    var dataResponse = await requestSender(dataOptions);
    dataResponse = JSON.parse(dataResponse);
    console.log(dataResponse);
    /*
    {
        login: 'Fb-dtalker',
        id: 34627521,
        node_id: 'MDQ6VXAccjQ0NdQ3NTMx',
        avatar_url: 'https://avatars.githubusercontent.com/u/44647531?v=4',
        gravatar_id: '',
        url: 'https://api.github.com/users/Fb-dtalker',
        html_url: 'https://github.com/Fb-dtalker',
        followers_url: 'https://api.github.com/users/Fb-dtalker/followers',
        following_url: 'https://api.github.com/users/Fb-dtalker/following{/other_user}',
        gists_url: 'https://api.github.com/users/Fb-dtalker/gists{/gist_id}',
        starred_url: 'https://api.github.com/users/Fb-dtalker/starred{/owner}{/repo}',
        subscriptions_url: 'https://api.github.com/users/Fb-dtalker/subscriptions',
        organizations_url: 'https://api.github.com/users/Fb-dtalker/orgs',
        repos_url: 'https://api.github.com/users/Fb-dtalker/repos',
        events_url: 'https://api.github.com/users/Fb-dtalker/events{/privacy}',
        received_events_url: 'https://api.github.com/users/Fb-dtalker/received_events',
        type: 'User',
        site_admin: false,
        name: null,
        company: null,
        blog: '',
        location: null,
        email: null,
        hireable: null,
        bio: null,
        twitter_username: null,
        public_repos: 17,
        public_gists: 0,
        followers: 0,
        following: 6,
        created_at: '2018-10-31T16:00:17Z',
        updated_at: '2022-12-16T02:49:41Z'
    }//为了账号安全实际的ID值进行了修改，不是正确的
    */

    ctx.body = JSON.stringify(dataResponse);
});

module.exports = router;

//参考链接：
//https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps
//https://blog.csdn.net/qq_21976063/article/details/104001431